package com.example.computer_exam_training_sys.service.impl;

import com.example.computer_exam_training_sys.entity.Knowledge;
import com.example.computer_exam_training_sys.mapper.KnowledgeMapper;
import com.example.computer_exam_training_sys.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class KnowledgeServiceImpl implements KnowledgeService {

    @Autowired
    private KnowledgeMapper knowledgeMapper;

    @Override
    public List<Knowledge> getKnowledgeTree(Long courseId) {
        List<Knowledge> allNodes = knowledgeMapper.getKnowledgeByCourseId(courseId);
        Map<Long, Knowledge> idMap = new HashMap<>();

        for (Knowledge node : allNodes) {
            idMap.put(node.getId(), node);
        }

        List<Knowledge> roots = new ArrayList<>();
        for (Knowledge node : allNodes) {
            if (node.getParentId() == null) {
                roots.add(node);
            } else {
                Knowledge parent = idMap.get(node.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }

        return roots;
    }
}